/**
 * @description 菜单管理页面
 * @author 李艳
 */
import {Component} from "react";
import {
  deleteNode,
  save, getMenuTree, move
} from "./MenuService";
import React from "react";
import {Button, Col, Modal, message, Row, Form, InputNumber} from "antd";

import {Input} from "antd/lib/index";

import {hide, show} from "../../../configs/SharedReducer";
import connect from "react-redux/es/connect/connect";
import EditMenuModal from "./EditMenuModal";
import {featureConfig} from "../../../configs/CommonComponentsConfig";
import SearchTable from "../../../commons/components/SearchTable";
import StandardTree, {getNodeByKey} from "../../../commons/components/StandardTree";
import HeadBreadcrumb from "../../../commons/components/breadcrumb/HeadBreadcrumb";
import {rowGutter} from "../../../configs/DefaultConfig";
import DetailCard from "../../../commons/components/DetailCard";
import PageOperateHoc from "../../../commons/components/PageOperateHoc";
import CheckAuth from "../../../commons/components/CheckAuth/index.jsx";

const FormItem = Form.Item;
const confirm = Modal.confirm;

class MenuView extends Component {
  constructor(props) {
    super(props);
    this.initPath = [{name: "菜单管理"}]
    this.state = {
      treeData: [],
      treeSelectedKeys: [],
      selectedNode: {},
      modalVisible: false,
      confirmLoading: false,
      isAddRoot: false
    }
  }

  componentWillMount() {
    this.getTreeData();
  }

  onModalRef = (ref) => {
    this.modalRef = ref;
  };

  //网络请求树控件数据（组织机构）
  getTreeData = (param) => {
    this.props.show();
    getMenuTree(param).then((result) => {
      this.setState({treeData: result});
    }).catch(err => {
    }).finally(() => {
      this.props.hide();
    });
  };

  //树节点选择触发
  onTreeSelect = (selectedKeys) => {
    let data = getNodeByKey(this.state.treeData, selectedKeys[0]);
    this.props.form.resetFields();
    this.setState({treeSelectedKeys: selectedKeys, selectedNode: data});
  };

  judgeTreeSelected = () => {
    if (this.state.selectedNode.id) {
      return true;
    }
    message.error("请选择一个节点");
    return false;
  };
  onAddRootClick = () => {
    this.setState({isAddRoot: true, modalVisible: true})
  };

  //增加节点
  onAddNodeClick = () => {
    if (!this.judgeTreeSelected()) return;
    this.setState({isAddRoot: false, modalVisible: true})
  };

  //删除节点
  onDeleteNodeClick = () => {
    if (!this.judgeTreeSelected()) return;
    let param = this.state.treeSelectedKeys[0];
    let thiz = this;
    confirm({
      title: "温馨提示",
      content: "删除后不可恢复，是否确定删除？",
      onOk() {
        deleteNode(param).then((result) => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "删除成功");
            thiz.props.form.resetFields();
            //请求treeData数据刷新本地数据
            thiz.getTreeData();
            thiz.props.form.resetFields()
            thiz.setState({selectedNode:{}})
          } else {
            message.error(result.message ? result.message : "删除失败");
          }
        }).catch((err) => {
        }).finally(() => {
        })
      },
      onCancel() {
      },
    });
  };

  handleEdit = () => {
    //表单数据同步
    if (this.modalRef && this.modalRef.props.form) {
      this.modalRef.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if (values.feature && !values.feature.id) {
            delete values.feature
          }
          this.setState({confirmLoading: true});
          save(values).then((result) => {
            if (result.status === "SUCCESS") {
              message.success(result.message ? result.message : "保存成功");
              //请求treeData数据刷新本地数据
              this.getTreeData();
              this.setState({confirmLoading: false, modalVisible: false});
            } else {
              message.error(result.message ? result.message : "保存失败")
              this.setState({confirmLoading: false});
            }
          }).catch(err => {
            this.setState({confirmLoading: false});
          })
        }
      })
    }
  };

  saveEdit = () => {
    //表单数据同步
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (values.feature && !values.feature.id) {
          delete values.feature
        }
        this.props.show();
        save(values).then((result) => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "保存成功");
            //请求treeData数据刷新本地数据
            this.getTreeData();
          } else {
            message.error(result.message ? result.message : "保存失败")
          }
        }).catch(err => {
        }).finally(() => {
          this.props.hide()//modal的进度条
        });
      }
    });
  };
  handleModalCancel = () => {
    this.setState({modalVisible: false})
  };

  render() {
    const {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {
        span: 3
      },
      wrapperCol: {
        span: 8
      },
    };

    const buttons = () => {
      return [
        <CheckAuth
          operateCode="BASIC-HTPZ-CDGL-ADDROOT"
          key={"elseButton"}
        >
          <Button key={"addRoot"} className={"primaryButton"} type={"primary"}
                  onClick={this.onAddRootClick}>新增根节点</Button>
        </CheckAuth>,

        <Button.Group key={"ButtonGroup"}>
          <CheckAuth
            operateCode="BASIC-HTPZ-CDGL-ADD"
            key={"addRoot"}
          >
            <Button onClick={this.onAddNodeClick}>新增节点</Button>
          </CheckAuth>
          <CheckAuth
            operateCode="BASIC-HTPZ-CDGL-DELETE"
            key={"delete"}
          >
            <Button onClick={this.onDeleteNodeClick}>删除</Button>
          </CheckAuth>
        </Button.Group>
      ]
    };

    const {selectedNode} = this.state;
    return (
      <HeadBreadcrumb
        // pathData={this.initPath}
        className={"allocation-page"}
        style={{overflow: "hidden"}}
      >
        <Row gutter={rowGutter} style={{height: "100%"}}>
          {/*左边的树状控件*/}
          <Col span={12} style={{height: "100%"}}>
            <DetailCard title="菜单" style={{height: "100%"}}>
              <StandardTree
                leftExtra={buttons()}
                onSelect={this.onTreeSelect}
                dadaSource={this.state.treeData}
                moveService={move}
                initService={this.getTreeData}/>
              <EditMenuModal
                modalVisible={this.state.modalVisible}
                confirmLoading={this.state.confirmLoading}
                handleOk={this.handleEdit}
                handleCancel={this.handleModalCancel}
                onRef={this.onModalRef}
                isAddRoot={this.state.isAddRoot}
                defaultValue={!this.state.isAddRoot ? selectedNode !== JSON.stringify("{}") ? selectedNode : {} : {}}
              />
            </DetailCard>
          </Col>

          {/*右边的控件*/}

          <Col span={12} style={{height: "100%"}}>
            <DetailCard
              className={"child-card"}
              style={{height: "100%"}}
              title={this.state.selectedNode.name ? this.state.selectedNode.name : "详细信息"}
            >
              <Form className="card-body-content" style={{height: "100%"}}>
                <FormItem
                  {...formItemLayout}
                  style={{display: 'none'}}
                  label="parentId">
                  {getFieldDecorator('parentId', {
                    initialValue: selectedNode.parentId ? selectedNode.parentId : "",
                  })(
                    <Input/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  style={{display: 'none'}}
                  label="id">
                  {getFieldDecorator('id', {
                    initialValue: selectedNode.id ? selectedNode.id : "",
                  })(
                    <Input/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="名称">
                  {getFieldDecorator('name', {
                    initialValue: selectedNode.name ? selectedNode.name : "",
                    rules: [{required: true, message: '请填写名称!'}]
                  })(
                    <Input/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="排序">
                  {getFieldDecorator('rank', {
                    initialValue: selectedNode.rank >= 0 ? selectedNode.rank : "",
                    rules: [{required: true, message: '请填写排序!'}]
                  })(
                    <InputNumber precision={0} min={0} max={999999999} style={{width: "100%"}}/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="图标样式">
                  {getFieldDecorator('iconCls', {
                    initialValue: selectedNode.iconCls ? selectedNode.iconCls : "",

                  })(
                    <Input/>
                  )}
                </FormItem>
                {selectedNode.children && selectedNode.children.length === 0 && <FormItem
                  {...formItemLayout}
                  label="功能项"
                >
                  {getFieldDecorator('feature.id', {
                    initialValue: selectedNode.feature ? selectedNode.feature.id : "",
                  })(
                    <SearchTable config={featureConfig} initValue={false}/>
                  )}
                </FormItem>}
                <br/>
                <Row>
                  <Col span={3}> </Col>
                  <Col span={8}>
                    <CheckAuth
                      operateCode={"BASIC-HTPZ-CDGL-SAVE"}>
                      <Button type={"primary"} onClick={this.saveEdit}>保存</Button>
                    </CheckAuth>
                  </Col>
                </Row>
              </Form>
            </DetailCard>
          </Col>
        </Row>
      </HeadBreadcrumb>

    )
  }
}

const mapStateToProps = (state) => {
  return {};
};

const mapDispatchToProps = (dispatch) => {
  return {
    show: () => {
      dispatch(show())
    },
    hide: () => {
      dispatch(hide())
    },
  }
};
MenuView = Form.create()(MenuView);
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PageOperateHoc(MenuView))

